﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;

namespace DFGK_WMS.Repository
{
    /// <summary>
    /// 盘点计划表
    /// </summary>
    public class StocktakingPlanRepository : BaseRepository<TStocktakingPlan>, IStocktakingPlanRepository
    {
        public StocktakingPlanRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        /// <summary>
        /// 添加盘点计划
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddStocktakingPlan(StocktakingPlanDto model)
        {
            try
            {
                //盘点计划：10-普通抽盘；20-临时抽盘；30-紧急抽盘；40-货主抽盘；50-库区抽盘；
                var planType = Context.TDictItems.Find(model.PlanType);

                //重复盘点：0-全部盘点；10-不盘30天已盘点的库区；20-不盘15天已盘点的库区；30-不盘7天内已盘点的库区；
                var repeat = Context.TDictItems.Find(model.Repeat);

                // 盘点工具：10-机器盘点；20-PDA；30-纸质；40-自定义；
                var means = Context.TDictItems.Find(model.Means);

                // 盘点粒度：0-全部盘点；10-抽查盘点（5%库位）；20-抽查盘点（25%库位）；30-抽查盘点（50%库位）
                var granularity = Context.TDictItems.Find(model.Granularity);

                //库房信息
                var house = Context.TWarehouses.Find(model.WarehouseId);
                if (house != null)
                {
                    model.WarehouseName = house.Name;
                }
                //库区信息
                var area = Context.TAreas.Find(model.AreaId);
                if (area != null)
                {
                    model.AreaName = area.Name;
                }

                var owner = Context.TOwners.Find(model.OwnerId);
                if (owner != null)
                {
                    model.OwnerName = owner.Name;
                }

                //状态默认为0
                model.Status = 0;
                //盘点计划默认为普通抽盘
                model.PlanType = 10;
                TStocktakingPlan StocktakingPlan = new TStocktakingPlan()
                {
                    BillSn = model.BillSn,
                    Name = model.Name,
                    BeginDate = model.BeginDate,
                    EndDate = model.EndDate,
                    WarehouseId = model.WarehouseId,
                    WarehouseName = model.WarehouseName,
                    AreaId = model.AreaId,
                    AreaName = model.AreaName,
                    OwnerId = model.OwnerId,
                    OwnerName = model.OwnerName,
                    Status = model.Status,
                    PlanType = model.PlanType,
                    Repeat = model.Repeat,
                    Means = model.Means,
                    MaxLocationCount = model.MaxLocationCount,
                    Granularity = model.Granularity,
                    GoodsAbc = model.GoodsAbc,
                    GoodsIds = model.GoodsIds,
                    GoodsNames = model.GoodsNames,
                    Remark = model.Remark,
                    CreateDate = DateTime.Now,
                    CreateUserId = model.CreateUserId,
                    CreateUserName = model.CreateUserName,
                };
                Context.TStocktakingPlans.Add(StocktakingPlan);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 删除盘点计划
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DeleteStocktakingPlan(int id)
        {
            try
            {
                var plan = Context.TStocktakingPlans.Find(id);
                if (plan != null)
                {
                    Context.TStocktakingPlans.Remove(plan);
                    return Context.SaveChanges() > 0;
                }

                return false;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        /// <summary>
        /// 修改盘点计划
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateStocktakingPlan(StocktakingPlanDto model)
        {
            try
            {
                // 根据传入的盘点计划ID查找对应的记录
                var plan = Context.TStocktakingPlans.FirstOrDefault(p => p.Id == model.Id);
                if (plan == null)
                {
                    throw new Exception("找不到要修改的盘点计划");
                }

                // 更新盘点计划的属性值
                plan.BillSn = model.BillSn;
                plan.Name = model.Name;
                plan.BeginDate = model.BeginDate;
                plan.EndDate = model.EndDate;
                plan.WarehouseId = model.WarehouseId;
                plan.WarehouseName = model.WarehouseName;
                plan.AreaId = model.AreaId;
                plan.AreaName = model.AreaName;
                plan.OwnerId = model.OwnerId;
                plan.OwnerName = model.OwnerName;
                plan.Status = model.Status;
                plan.PlanType = model.PlanType;
                plan.Repeat = model.Repeat;
                plan.Means = model.Means;
                plan.MaxLocationCount = model.MaxLocationCount;
                plan.Granularity = model.Granularity;
                plan.GoodsAbc = model.GoodsAbc;
                plan.GoodsIds = model.GoodsIds;
                plan.GoodsNames = model.GoodsNames;
                plan.Remark = model.Remark;
                plan.ModifyDate = DateTime.Now; // 使用当前时间作为修改时间
                plan.ModifyUserId = model.ModifyUserId;

                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="houseId"></param>
        /// <param name="areaId"></param>
        /// <param name="billSn"></param>
        /// <param name="status"></param>
        /// <param name="toalCount"></param>
        /// <returns></returns>
        public List<TStocktakingPlan> GetAllStocktakingPlans(int? houseId, int? areaId, string? billSn, int? status, int pageIndex, int pageSize, out int toalCount)
        {
            var query = Context.TStocktakingPlans.AsQueryable();

            // 筛选仓库
            if (houseId.HasValue && houseId.Value != 0)
            {
                query = query.Where(m => m.WarehouseId == houseId.Value);
            }

            // 筛选库区
            if (areaId.HasValue && areaId.Value != 0)
            {
                query = query.Where(m => m.AreaId == areaId.Value);
            }

            // 筛选单号
            if (!string.IsNullOrEmpty(billSn))
            {
                query = query.Where(m => m.BillSn == billSn);
            }

            // 筛选状态
            if (status.HasValue && status.Value != 0)
            {
                query = query.Where(m => m.Status == status.Value);
            }

            toalCount = query.Count();
            query = query.OrderByDescending(x=>x.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return query.ToList();
        }

        /// <summary>
        /// 根据Id获取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public TStocktakingPlan GetStocktakingPlan(int id)
        {
            try
            {
                return Context.TStocktakingPlans.Find(id);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateState(ReceivingOrderDetailDto model)
        {
            var state = Context.TStocktakingPlans.Find(model.Id);
            if (state is null)
            {
                return false;
            }
            if ((model.state == 1 || model.state == 3) && model.JobNo is not null && model.NowUserRealName is not null)
            {
                var user = Context.TUsers.AsNoTracking().Where(u => u.RealName == model.NowUserRealName && u.JobNo == model.JobNo).FirstOrDefault();
                if (user is null)
                {
                    return false;
                }
                if (model.state == 1)
                {
                    state.Status = 10;
                }
                if (model.state == 3)
                {
                    state.Status = 30;
                }
            }

            if (model.state == 2)
            {
                state.Status = 20;
            }
            Context.TStocktakingPlans.Update(state);
            return Context.SaveChanges() > 0;
        }
    }
}